package com.daqian.chance.common.util;

import com.daqian.chance.common.base.BaseDTO;
import org.springframework.beans.BeanUtils;

/**
 * @author: daqian
 * @date: 2019/7/9 15:54
 */
public class DtoUtil {
    /**
     * 将DTO转换成实体类
     *
     * @param dto
     * @param entity
     * @return E
     * @author daqian
     * @date 2019/7/9 15:37
     */
    public static <D extends BaseDTO, E> E convertToEntity(D dto, E entity) {
        if (dto == null) {
            return null;
        }
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    /**
     * 将实体类转换成DTO
     *
     * @param dto
     * @param entity
     * @return D
     * @author daqian
     * @date 2019/7/9 15:44
     */
    public static <D extends BaseDTO, E> D convertToDto(D dto, E entity) {
        if (entity == null) {
            return null;
        }
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    /**
     * 将DTO转换成实体类
     *
     * @param dto
     * @param eClass
     * @return E
     */
    public static <D extends BaseDTO, E> E convertToEntity(D dto, Class<E> eClass) {
        if (dto == null) {
            return null;
        }
        E entity = null;
        try {
            entity = eClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    /**
     * 将实体类转换成DTO
     *
     * @param entity
     * @param dClass
     * @return D
     */
    public static <D extends BaseDTO, E> D convertToDto(E entity, Class<D> dClass) {
        if (entity == null) {
            return null;
        }
        D dto = null;
        try {
            dto = dClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }
}
